package cmd

import (
	"context"
	"ultone/internal/api"
	"ultone/internal/controller"
	"ultone/internal/database/cache"
	"ultone/internal/database/db"
	"ultone/internal/log"
	"ultone/internal/model"
	"ultone/internal/opt"
	"ultone/internal/tool"
)

var (
	filename string
)

func execute(ctx context.Context) error {
	tool.Must(opt.Init(filename))
	tool.Must(db.Init(ctx, opt.Cfg.DB.Uri))
	tool.Must(cache.Init())

	// todo: if elastic search required
	//tool.Must(es.Init(ctx, opt.Cfg.ES.Uri))
	// 或者使用 https://github.com/olivere/elastic
	//tool.Must(elastic.Init(ctx, opt.Cfg.ES.Uri))

	// todo: if nebula required
	// tool.Must(nebula.Init(ctx, opt.Cfg.Nebula))

	tool.Must(model.Init(db.Default.Session()))
	tool.Must(controller.Init(ctx))
	tool.Must(api.Start(ctx))

	// todo: if need some cli operation, should start local unix rpc svc
	//tool.Must(unix.Start(ctx))

	<-ctx.Done()

	log.Warn(ctx, "received quit signal...(2s)")
	<-tool.Timeout(2).Done()

	return nil
}

func Execute(ctx context.Context) error {
	return rootCommand.ExecuteContext(ctx)
}
